<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\OperationLog;

class AdminOperationLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user_id = 0;
        $arr = array();
        $arr = Auth::guard('admin')->user()->toArray();
//        if(Auth::check()) {
//            $user_id = (int) Auth::id();
//            $user_id = (int)Admin::id();
//        }
//        dd($arr['id']);
//        $_SERVER['admin_uid'] = $user_id;
        $_SERVER['admin_uid'] = $arr['id'];

        if('GET' != $request->method()){
            $input = $request->all();
            $log = new OperationLog(); # 提前创建表、model
            $log->uid = $arr['id'];
            $log->username = $arr['username'];
            $log->path = $request->path();
//            dd($log->path);
//            dd($this->cut_str($log->path,'/',3));
            $log->model = $this->cut_str($log->path,'/',2);
            $log->info_id = $this->cut_str($log->path,'/',3);
            if($log->info_id == 'error'){
                $log->info_id = null;
            }
            $log->method = $request->method();
            $log->ip = $request->ip();
//            $log->sql = '';
            $log->input = json_encode($input, JSON_UNESCAPED_UNICODE);
            $log->save();   # 记录日志
        }
        return $next($request);

    }

    function cut_str($str,$sign,$number){
        $array=explode($sign, $str);
        $length=count($array);
        if($number<0){
            $new_array=array_reverse($array);
            $abs_number=abs($number);
            if($abs_number>$length){
                return 'error';
            }else{
                return $new_array[$abs_number-1];
            }
        }else{
            if($number>=$length){
                return 'error';
            }else{
                return $array[$number];
            }
        }
    }
}
